<template>
  <el-form :model="detailForm" ref="detailForm" :inline="false">
    <el-card class="box-card" shadow="never">
      <div slot="header" class="header-card">
        <span class="header-card-title">上传保单</span>
      </div>
      <el-row>
        <el-col>
          <el-form-item>
            <el-button type="primary" size="small" :disabled="tableData.length === 0"
              @click="handleBatch">批量处理时间</el-button>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col>
          <el-table ref="multipleTable" :data="detailForm.tableData" border tooltip-effect="dark" style="width: 100%"
            @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="30" />
            <el-table-column align="center" label="操作" width="50">
              <template #default="{row,$index}">
                <el-button size="mini" type="text"  @click="handleEdit(row,$index)">编辑
                </el-button>
              </template>
            </el-table-column>
            <el-table-column align="center" label="车牌号" prop="carNo" min-width="180" />

            <el-table-column align="center" label="车架号" prop="vinNo" min-width="180" />

            <el-table-column align="center" label="商业险实际开始时间" prop="syxActualBeginTime" min-width="180">
              <template #default="{row,$index}">
                <el-form-item class="formTable" :prop="'tableData.'+$index+'.syxActualBeginTime'"
                  :rules="{required: isEdit,trigger: 'blur'}">
                  <el-date-picker v-model="row.syxActualBeginTime" type="date" placeholder="请选择商业险实际开始时间"
                  @change="changeData(detailForm.tableData,row.syxActualBeginTime,$index,'syxActualEndTime')"
                    v-if="isEdit   " value-format='yyyy-MM-dd' style="width: 100%;">
                  </el-date-picker>
                  <span v-else>{{ row.syxActualBeginTime }}</span>
                </el-form-item>
              </template>
            </el-table-column>

            <el-table-column align="center" label="商业险实际结束时间" min-width="180" prop="syxActualEndTime">
              <template #default="{row,$index}">
                <el-form-item class="formTable" :prop="'tableData.'+$index+'.syxActualEndTime'"
                  :rules="{required: isEdit,trigger: 'blur'}">
                  <el-date-picker v-model="row.syxActualEndTime" type="date" placeholder="请选择商业险实际结束时间" v-if="isEdit   "
                    value-format='yyyy-MM-dd' style="width: 100%;">
                  </el-date-picker>
                  <span v-else>{{ row.syxActualEndTime }}</span>
                </el-form-item>
              </template>
            </el-table-column>

            <el-table-column align="center" label="商业险保单号" prop="syxPolicyCode" min-width="160">
              <template #default="{row,$index}">
                <el-form-item class="formTable" :prop="'tableData.'+$index+'.syxPolicyCode'"
                  :rules="{required: isEdit,trigger: 'blur'}">
                  <el-input v-if="isEdit   " v-model="row.syxPolicyCode" 
                  @change="handlePolicyCode(row.syxPolicyCode,$index,'syxPolicyCode','jqxPolicyCode')"
                  placeholder="请输入商业险保单号" size="mini" />
                  <span v-else>{{ row.syxPolicyCode }}</span>
                </el-form-item>
              </template>
            </el-table-column>

            <el-table-column align="center" label="交强险实际开始时间" prop="jqxActualBeginTime" min-width="180">
              <template #default="{row,$index}">
                <el-form-item class="formTable" :prop="'tableData.'+$index+'.jqxActualBeginTime'"
                  :rules="{required: isEdit,trigger: 'blur'}">
                  <el-date-picker v-model="row.jqxActualBeginTime" type="date" 
                  @change="changeData(detailForm.tableData,row.jqxActualBeginTime,$index,'jqxActualEndTime')"
                  placeholder="请选择交强险起保日" v-if="isEdit   "
                    value-format='yyyy-MM-dd' style="width: 100%;">
                  </el-date-picker>
                  <span v-else>{{ row.jqxActualBeginTime }}</span>
                </el-form-item>
              </template>
            </el-table-column>

            <el-table-column align="center" label="交强险实际结束时间" prop="jqxActualEndTime" min-width="180">
              <template #default="{row,$index}">
                <el-form-item class="formTable" :prop="'tableData.'+$index+'.jqxActualEndTime'"
                  :rules="{required: isEdit,trigger: 'blur'}">
                  <el-date-picker v-model="row.jqxActualEndTime" type="date" placeholder="请选择交强险到期日" v-if="isEdit   "
                    value-format='yyyy-MM-dd' style="width: 100%;">
                  </el-date-picker>
                  <span v-else>{{ row.jqxActualEndTime }}</span>
                </el-form-item>
              </template>
            </el-table-column>

            <el-table-column align="center" label="交强险保单号" prop="jqxPolicyCode" min-width="160">
              <template #default="{row,$index}">
                <el-form-item class="formTable" :prop="'tableData.'+$index+'.jqxPolicyCode'"
                  :rules="{required: isEdit,trigger: 'blur'}">
                  <el-input v-if="isEdit   " v-model="row.jqxPolicyCode" 
                  @change="handlePolicyCode(row.jqxPolicyCode,$index,'jqxPolicyCode','syxPolicyCode')"
                  placeholder="请输入交强险保单号" size="mini" />
                  <span v-else>{{ row.jqxPolicyCode }}</span>
                </el-form-item>
              </template>
            </el-table-column>

            <el-table-column align="center" label="商业险保单" width="160">
              <template #default="{row}">
                <el-popover placement="right" trigger="click">
                  <image-common v-model="row.syxPolicyUrl" :disabled="!isEdit" :up-type="2"/>
                  <el-button type="text" slot="reference">
                    <span v-if="row.syxBool" style="color: red;padding-left: 20px">请上传商业险保单</span>
                    <span v-else>上传</span>
                  </el-button>
                </el-popover>
              </template>
            </el-table-column>

            <el-table-column align="center" label="交强险保单" width="160">
              <template #default="{row}">
                <el-popover placement="right" trigger="click">
                  <image-common v-model="row.jqxPolicyUrl" :disabled="!isEdit" :up-type="2"/>
                  <el-button type="text" slot="reference">
                    <span v-if="row.jqxBool" style="color: red;padding-left: 20px">请上传交强险保单</span>
                    <span v-else>上传</span>
                  </el-button>
                </el-popover>
              </template>
            </el-table-column>
          </el-table>
        </el-col>
      </el-row>

    </el-card>

    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" class="dialogForm" :rules="rules" label-width="160px">
        <el-row v-if="title === '编辑'">
          <el-col :span="12">
            <el-form-item label="车架号:" prop="vinNo">
              <span>{{ form.vinNo }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="车牌号:" prop="carNo">
              <span>{{ form.carNo }}</span>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="title === '编辑'">
          <el-col :span="12">
            <el-form-item label="商业险保单号:" prop="syxPolicyCode">
              <el-input v-if="isEdit" v-model="form.syxPolicyCode" placeholder="请输入商业险保单号" size="mini" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="交强险保单号:" prop="jqxPolicyCode">
              <el-input v-if="isEdit" v-model="form.jqxPolicyCode" placeholder="请输入交强险保单号" size="mini" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="商业实际开始使时间:" prop="syxActualBeginTime">
              <el-date-picker v-model="form.syxActualBeginTime" type="date" placeholder="请选择商业实际开始使时间"
              @change="handleDialogDate(form.syxActualBeginTime,'syxActualEndTime')"
                value-format='yyyy-MM-dd' style="width: 100%;">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="商业实际结束使时间:" prop="syxActualEndTime">
              <el-date-picker v-model="form.syxActualEndTime" type="date" placeholder="请选择商业实际结束使时间"
                value-format='yyyy-MM-dd' style="width: 100%;">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="交强实际开始使时间:" prop="jqxActualBeginTime">
              <el-date-picker v-model="form.jqxActualBeginTime" type="date" placeholder="请选择交强实际开始使时间"
              @change="handleDialogDate(form.jqxActualBeginTime,'jqxActualEndTime')"
                value-format='yyyy-MM-dd' style="width: 100%;">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="交强实际结束使时间:" prop="jqxActualEndTime">
              <el-date-picker v-model="form.jqxActualEndTime" type="date" placeholder="请选择交强实际结束使时间"
                value-format='yyyy-MM-dd' style="width: 100%;">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row v-if="title === '编辑'">
          <el-col :span="12">
            <el-form-item label="商业险保单:" prop="syxPolicyUrl">
              <image-common v-model="form.syxPolicyUrl" :limit="20" :disabled="!isEdit" :upType="2" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="交强险保单:" prop="jqxPolicyUrl">
              <image-common v-model="form.jqxPolicyUrl" :limit="20" :disabled="!isEdit" :upType="2" />
            </el-form-item>
          </el-col>
        </el-row>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>
  </el-form>
</template>

<script>
import { effectDate } from "@/utils/libs/effectDate.js";
export default {
  name: "uploadPolicy", //上传保单
  props: {
    value: {
      type: Object,
      default: {},
    },
    state: {
      type: String,
      default: "",
    },
    activityId: {
      type: String,
      default: "",
    },
    pageConfig: {
      type: Array,
      default: () => {
        return [];
      },
    },
  },

  computed: {
    detailForm: {
      get() {
        let that = this;
        const proxy = new Proxy(that.value, {
          get(target, key) {
            return Reflect.get(target, key);
          },
          set(target, key, value) {
            that.$emit("input", { ...target, [key]: value });
            return true;
          },
        });
        return proxy;
      },
    },
    labelPosition() {
      if (this.state === "write") {
        return "top";
      } else {
        return "right";
      }
    },
    isEdit() {
      let bool;
      switch (this.state) {
        case "write":
          bool = true;
          break;
        case "disabled":
          bool = false;
          break;
        case "readonly":
          bool = false;
          break;
      }
      return bool;
    },
  },
  watch: {
    "value.tableData": {
      handler(val) {
        if (val) {
          val.forEach((item) => {
            if (item.syxPolicyUrl) {
              item.syxBool = false;
            }
            if (item.jqxPolicyUrl) {
              item.jqxBool = false;
            }
          });
        }
      },
      immediate: true,
      deep: true,
    },
  },
  data() {
    var jqxStart = (rule, value, callback) => {
      let that = this;
      effectDate(
        rule,
        value,
        callback,
        that.form.jqxActualBeginTime,
        that.form.jqxActualEndTime,
        "交强险起保日",
        "交强险到期日"
      );
    };
    var jqxEnd = (rule, value, callback) => {
      let that = this;
      effectDate(
        rule,
        value,
        callback,
        that.form.jqxActualBeginTime,
        that.form.jqxActualEndTime,
        "交强险起保日",
        "交强险到期日"
      );
    };
    var syxStart = (rule, value, callback) => {
      let that = this;
      effectDate(
        rule,
        value,
        callback,
        that.form.syxActualBeginTime,
        that.form.syxActualEndTime,
        "商业险起保日",
        "商业险到期日"
      );
    };
    var syxEnd = (rule, value, callback) => {
      let that = this;
      effectDate(
        rule,
        value,
        callback,
        that.form.syxActualBeginTime,
        that.form.syxActualEndTime,
        "商业险起保日",
        "商业险到期日"
      );
    };
    var syxCode = (rule, value, callback) => {
      let that = this;
      if (value === " " || value === null) {
        callback(new Error("请输入保单号"));
      } else {
        let index_ = this.value.tableData.findIndex(
            (item, i) => (i !== that.index && value === item.syxPolicyCode) || value === item.jqxPolicyCode
        )
        if (index_ !== -1) {
          callback(new Error("商业险保单号冲突,请核实"));
        } else {
          callback();
        }
      }
    };

    var jaxCode = (rule, value, callback) => {
      let that = this;
      if (value === " " || value === null) {
        callback(new Error("请输入保单号"));
      } else {
        let index_ = this.value.tableData.findIndex(
            (item, i) => (i !== that.index && value === item.jqxPolicyCode) || value === item.syxPolicyCode
        )
        if (index_ !== -1) {
          callback(new Error("交强险保单号冲突,请核实"));
        } else {
          callback();
        }
      }
    };
    return {
      title: "",
      open: false,
      form: {},
      rules: {
        syxPolicyCode: [
          { required: true, validator: syxCode, trigger: "blur" },
        ],
        jqxPolicyCode: [
          { required: true, validator: jaxCode, trigger: "blur" },
        ],
        syxActualBeginTime: [
          { required: true, validator: syxStart, trigger: "blur" },
        ],
        syxActualEndTime: [
          { required: true, validator: syxEnd, trigger: "blur" },
        ],
        jqxActualBeginTime: [
          { required: true, validator: jqxStart, trigger: "blur" },
        ],
        jqxActualEndTime: [
          { required: true, validator: jqxEnd, trigger: "blur" },
        ],
        syxPolicyUrl: [
          { required: true, message: "请上传商业险保单", trigger: "blur" },
        ],
        jqxPolicyUrl: [
          { required: true, message: "请上传交强险保单", trigger: "blur" },
        ],
      },
      index: 0,
      tableData: [],
      activityName: "",
      shopInsuranceBool: false, //店保
      ourCompanyBool1: false, //我司
      ourCompanyBool2: false, //我司
      formId: "",
    };
  },
  created() {
    this.$nextTick(() => {
      this.handleTime(
          this.value.jqxExpectBeginTime,
          this.value.jqxExpectEndTime,
          this.value.syxExpectBeginTime,
          this.value.syxExpectEndTime,
      )
    })
  },
  methods: {
    handleTime(syxStart, syxEnd, jqxStart, jqxEnd,) {
      this.value.tableData.forEach(item => {
        item.syxActualBeginTime = syxStart
        item.syxActualEndTime = syxEnd
        item.jqxActualBeginTime = jqxStart
        item.jqxActualEndTime = jqxEnd
      })
    },

    
    handlePolicyCode(val, i, key, key_) {
      if (val) {
        this.handleRepeat(i, key, val, key_);
      }
    },

    handleRepeat(index, key, val, key_) {
      let index_ = this.value.tableData.findIndex(
          (item, i) => (i !== index && val === item[key]) || val === item[key_]
      );
      if (index_ !== -1) {
        this.$set(this.value.tableData[index], [key], "");
      } else {
        this.$set(this.value.tableData[index], [key], val);
      }
    },

    handleDialogDate(time, key) {
      let timeDate = this.addOneMonth(time, 12);
      this.$set(this.form, [key], timeDate);
    },

    changeData(list, time, i, key) {
      let timeDate = this.addOneMonth(time, 12);
      this.$set(this.detailForm.tableData, i, {
        ...this.detailForm.tableData[i],
        [key]: timeDate,
      });
    },

    addOneMonth(dateString, month) {
      const date = new Date(dateString);
      date.setMonth(date.getMonth() + Number(month));
      date.setDate(date.getDate() - 1);
      return date.toISOString().split("T")[0]; // 返回YYYY-MM-DD格式的日期字符串
    },

    handleBatch() {
      if (this.tableData.length > 0) {
        this.title = "批量编辑保单时间";
        this.form = {
          syxActualBeginTime: "",
          syxActualEndTime: "",
          jqxActualBeginTime: "",
          jqxActualEndTime: "",
        };
        this.open = true;
      }
    },

    handleSelectionChange(val) {
      this.tableData = val.map((a) => {
        return a.workId;
      });
    },
    handleEdit(row, index) {
      this.title = "编辑";
      this.open = true;
      this.form = row;
      this.index = index;
    },
    cancel() {
      this.open = false;
      this.form = {};
    },
    submitForm() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          if (this.title === "编辑") {
            this.detailForm.tableData[this.index] = this.form;
          }
          if (this.title === "批量编辑保单时间") {
            for (let i = 0; i < this.tableData.length; i++) {
              let indexL = this.detailForm.tableData.findIndex(
                (a) => a.workId === this.tableData[i]
              );
              if (indexL !== -1) {
                this.detailForm.tableData[indexL].syxActualBeginTime =
                  this.form.syxActualBeginTime;
                this.detailForm.tableData[indexL].syxActualEndTime =
                  this.form.syxActualEndTime;
                this.detailForm.tableData[indexL].jqxActualBeginTime =
                  this.form.jqxActualBeginTime;
                this.detailForm.tableData[indexL].jqxActualEndTime =
                  this.form.jqxActualEndTime;
              }
            }
          }
          this.open = false;
        }
      });
    },

    valid() {
      let arr = [
        this.handleUrl(this.value.tableData, "syxPolicyUrl", "syxBool"),
        this.handleUrl(this.value.tableData, "jqxPolicyUrl", "jqxBool"),
      ];
      return new Promise((resolve, reject) => {
        this.$refs.detailForm.validate((valid) => {
          Promise.all(arr)
              .then(() => {
                resolve(valid && true);
              })
              .catch(() => {
                reject();
              });
        });
      });
    },

    handleUrl(list, key, str) {
      return new Promise((resolve, reject) => {
        let boole;
        list.forEach((item, index) => {
          if (item[key]) {
            this.$set(list[index], [str], false);
            boole = true;
          } else {
            this.$set(list[index], [str], true);
            boole = false;
          }
        });
        if (boole) {
          resolve();
        } else {
          reject();
        }
      });
    },
    
  },
};
</script>

<style lang="scss" scoped>
@import "@/styles/cwgd/formScss.scss";

::v-deep.el-opover-img {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 0;
}

::v-deep.component-upload-image {
  margin-left: 25px !important;
}
</style>

